<template>
  <div class="users-container">
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="handleAddUser">
        添加用户
      </el-button>
    </div>

    <!-- 搜索栏（匹配后端模糊查询参数） -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户账号">
          <!-- 后端模糊查询字段为 userAccount，此处对应绑定 -->
          <el-input v-model="searchForm.userAccount" placeholder="请输入用户账号" />
        </el-form-item>
        <el-form-item label="禁言状态">
          <!-- 后端 isWord 字段：0-可用（不禁言），1-不可用（禁言） -->
          <el-select v-model="searchForm.isWord" placeholder="请选择禁言状态" clearable>
            <el-option label="正常" :value="false" />
            <el-option label="禁言" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 用户新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
      >
        <el-form-item label="用户账号" prop="userAccount">
          <el-input v-model="userForm.userAccount" placeholder="请输入用户账号" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="userName">
          <el-input v-model="userForm.userName" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="userForm.userEmail" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="用户角色" prop="userRole">
          <el-select v-model="userForm.userRole" placeholder="请选择用户角色">
            <el-option label="管理员" :value="0" />
            <el-option label="普通用户" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="禁言状态" prop="isWord">
          <el-select v-model="userForm.isWord" placeholder="请选择禁言状态">
            <el-option label="正常" :value="false" />
            <el-option label="禁言" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="userAvatar">
          <el-input v-model="userForm.userAvatar" placeholder="请输入头像URL" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 用户列表（匹配后端返回的 User 实体字段） -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="users"
        style="width: 100%"
        :row-key="(row) => row.id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <!-- 后端头像字段为 userAvatar -->
            <el-avatar :src="row.userAvatar" :size="40">
              {{ row.userName?.charAt(0) }}
            </el-avatar>
          </template>
        </el-table-column>
        <!-- 后端用户账号字段为 userAccount，用户昵称为 userName -->
        <el-table-column prop="userAccount" label="用户账号" />
        <el-table-column prop="userName" label="用户昵称" />
        <el-table-column prop="userEmail" label="邮箱" />
        <el-table-column prop="userRole" label="角色" width="100">
          <template #default="{ row }">
            <!-- 后端 userRole：0-管理员，1-普通用户 -->
            <el-tag :type="row.userRole === 0 ? 'danger' : 'primary'">
              {{ row.userRole === 0 ? '管理员' : '用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isWord" label="禁言状态" width="100">
          <template #default="{ row }">
            <!-- 后端 isWord：0-可用（不禁言），1-不可用（禁言） -->
            <el-tag :type="row.isWord === false ? 'success' : 'danger'">
              {{ row.isWord === false ? '正常' : '已禁言' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件（匹配后端 pageNum 和 pageSize） -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import dayjs from 'dayjs'

// 数据定义
const users = ref<any[]>([])
const loading = ref(false)
const currentPage = ref(1) // 对应后端 pageNum
const pageSize = ref(5)    // 对应后端 pageSize（默认值与后端保持一致）
const total = ref(0)

// 弹窗相关数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const userFormRef = ref()

// 用户表单数据
const userForm = reactive({
  id: undefined as number | undefined,
  userAccount: '',
  userName: '',
  userEmail: '',
  userRole: 1, // 默认普通用户
  isWord: false, // 默认不禁言
  userAvatar: ''
})

// 表单验证规则
const userFormRules = {
  userAccount: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    { min: 3, max: 20, message: '用户账号长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  userName: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '用户昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  userEmail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email' as const, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  userRole: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ],
  isWord: [
    { required: true, message: '请选择禁言状态', trigger: 'change' }
  ]
}

// 搜索表单（匹配后端接口参数）
const searchForm = reactive({
  userAccount: '', // 后端模糊查询参数 userAccount
  isWord: undefined as boolean | undefined // 后端禁言状态参数 isWord
})

// 时间格式化（匹配后端 LocalDateTime 格式）
const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 加载用户列表（调用后端 /user/list 接口）
const loadUsers = async () => {
  try {
    loading.value = true
    // 构造请求参数（与后端接口参数对应）
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      isWord: searchForm.isWord,
      userAccount: searchForm.userAccount
    }
    console.log('请求参数:', params);
    // 调用后端分页+模糊查询接口
    const res = await request.get(`/user/list`, { params }) as any
    console.log('后端返回数据:', res);
    // request 工具的响应拦截器已经处理了 code 检查，返回的是 data 字段
    // 后端返回格式为 Result.success(data)，data 为 PageView 对象
    // PageView 结构：{ pageNum, pageSize, totalPage, allRow, data }
    // 确保数据是数组
    const dataArray = Array.isArray(res.data.data) ? res.data.data : []
    users.value = dataArray // PageView 中的数据列表
    total.value = res.data.allRow || 0   // PageView 中的总条数
    console.log('设置的数据:', { users: users.value, total: total.value });
  } catch (error: any) {
    console.error('请求错误:', error);
    ElMessage.error('网络错误，获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮
const handleSearch = () => {
  currentPage.value = 1 // 重置为第一页
  loadUsers()
}

// 重置按钮
const handleReset = () => {
  searchForm.userAccount = ''
  searchForm.isWord = undefined
  currentPage.value = 1
  loadUsers()
}

// 重置用户表单
const resetUserForm = () => {
  userForm.id = undefined
  userForm.userAccount = ''
  userForm.userName = ''
  userForm.userEmail = ''
  userForm.userRole = 1
  userForm.isWord = false
  userForm.userAvatar = ''
}

// 弹窗关闭处理
const handleDialogClose = () => {
  resetUserForm()
  userFormRef.value?.resetFields()
}

// 添加用户
const handleAddUser = () => {
  dialogTitle.value = '添加用户'
  dialogVisible.value = true
  resetUserForm()
}

// 编辑用户
const handleEdit = (user: any) => {
  dialogTitle.value = '编辑用户'
  dialogVisible.value = true
  // 回显用户数据
  userForm.id = user.id
  userForm.userAccount = user.userAccount
  userForm.userName = user.userName
  userForm.userEmail = user.userEmail
  userForm.userRole = user.userRole
  userForm.isWord = user.isWord
  userForm.userAvatar = user.userAvatar || ''
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await userFormRef.value?.validate()
    
    submitLoading.value = true
    
    if (userForm.id) {
      // 编辑用户
      await request.put('/user/update', userForm)
      ElMessage.success('用户信息修改成功')
    } else {
      // 新增用户
      await request.post('/user/add', userForm)
      ElMessage.success('新增用户成功')
    }
    
    dialogVisible.value = false
    loadUsers() // 刷新列表
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}



// 删除用户（对接后端 /user/delete/{id} 接口）
const handleDelete = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${user.userAccount}"吗？此操作不可恢复！`,
      {
        title: '确认删除',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用后端删除接口
    await request.delete(`/user/delete/${user.id}`)
    ElMessage.success('删除成功')
    loadUsers() // 刷新列表
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 分页尺寸变化
const handleSizeChange = (size: number) => {
  console.log('分页尺寸变化:', size);
  pageSize.value = size
  currentPage.value = 1
  loadUsers()
}

// 分页页码变化
const handleCurrentChange = (page: number) => {
  console.log('分页页码变化:', page);
  currentPage.value = page
  loadUsers()
}

// 页面加载时获取用户列表
onMounted(() => {
  // 确保数据是数组
  if (!Array.isArray(users.value)) {
    users.value = []
  }
  loadUsers()
})
</script>

<style scoped lang="scss">
.users-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: $text-color;
    }
  }
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  .pagination-wrapper {
    margin-top: 20px;
    text-align: center;
  }
}
</style> 
